<template>
	<view class="canvas">
		<canvas :style="{ width: canvasSize.width,height: canvasSize.height}" canvas-id="myCanvas" ></canvas>
	</view>
</template>

<script>
	export default {
		data(){
			return {
				imgUrls: [],
				canvasSize:{
					width: '',
					height: ''
				}
			}
		},
		methods:{
			// 开始压缩
			compress(res){
				return new Promise( async(resolve, reject) => {
					let imgInfo = await this.getImageInfo(res.tempFilePaths[0])
					if(!imgInfo){
						console.log('获取图片信息异常')
						return;
					}
					// 当获取图片的大小 小于 100K 直接返回
					let size = Math.floor(res.tempFiles[0].size / 1024);
					if(size < 100){
						resolve(res.tempFilePaths[0]);
						return;
					}
					
					// 设置最大 & 最小 尺寸
					const maxSize = 800;
					const minSize = 640;
					
					// 当前图片尺寸
					let {width,height} = imgInfo;
					// #ifdef H5
					if(width <= minSize && height <= minSize){
						resolve(res.tempFilePaths[0]);
						return;
					}
					// #endif
					
					// 最大尺寸计算
					if (width > maxSize || height > maxSize) {
						if (width > height) {
							height = Math.floor(height / (width / maxSize));  	// 等比例的计算 新高
							width = maxSize;
						} else {
							width = Math.floor(width / (height / maxSize));		// 等比例的计算 新宽
							height = maxSize;
						}
					}
					// 设置画布尺寸
					this.$set(this,"canvasSize",{
						width: `${width}rpx`,
						height: `${height}rpx`
					})
					
					setTimeout(_=>{
						const ctx = uni.createCanvasContext('myCanvas', this);
						ctx.drawImage(imgInfo.path, 0, 0, uni.upx2px(width), uni.upx2px(height))
						ctx.draw(false, ()=>{
							uni.canvasToTempFilePath({
									x:0,
									y:0,
									canvasId: 'myCanvas',
									fileType: 'jpg',
									quality: 0.9,
									success: r => {
										resolve(r.tempFilePath);
									},
									fail:(err)=>{
										console.log(err,'出错');
									}
								},this)
						})
					},300)
				})
			},
			
			// 获取图片信息
			getImageInfo(src){
				return new Promise((resolve, reject)=>{
					uni.getImageInfo({
						src,
						success: info=> { resolve( info )},
						fail: () => { reject( null ) }
					})
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.canvas{position: fixed;top: -99999rpx;}
</style>
